<script lang="ts" setup>
import {ref} from "vue";
import Edit from './edit.vue';
import DataTable from  '@/components/data-table/index.vue'
import {service} from "@/utils";

defineOptions({name: "SystemRole"})

const dataTableRef = ref<InstanceType<typeof DataTable>>();
const editRef = ref<InstanceType<typeof Edit>>();
const params = ref({
    roleName: undefined,
    alias: undefined,
})
const columns = ref([
    {prop: "roleId", label: "ID", width: 90},
    {prop: "roleName", label: "英文名称", align: 'left', minWidth: 190},
    {prop: "alias", label: "中文名称", align: 'left', minWidth: 190},
    {prop: "remark", label: "备注", align: 'left', minWidth: 190},
    {prop: "createTime", label: "创建时间", width: 190},
    {
        type: "action", width: 190,
        render: [
            {auth: 'role:update', onClick: ({row}: any) => onEdit('update', row)},
            {auth: 'role:delete', onClick: ({row}: any) => onDelete([row]), type:"danger"}
        ]
    }
])

// 表单
function onEdit (type: any, row?: any) {
    editRef.value?.open({
        data: row,
        type: type === 'update' ? 'put' : 'post',
        confirm: (resolve: (value: any)=> void, form: any, operate: AxiosMethod) => {
            service[operate]('/role', JSON.stringify(form), {
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(({code}) => {
                if (code === 200){
                    dataTableRef.value?.refresh()
                }
                resolve(code);
            })
        }
    });
}

// 删除
function onDelete (rows: { roleId: string, roleName: string }[]) {
    const names = rows.map(item => item.roleName);
    const roles = rows.map(item => item.roleId);
    service.confirm(`确定对角色名称[${names.join(',')}]进行${names.length === 1 ? '删除' : '批量删除'}操作,该操作不可逆?`, {
        url: '/role',
        data: {roleIds: roles},
        success: dataTableRef.value?.refresh
    })
}
</script>
<template>
    <main-page>
        <data-table ref="dataTableRef" :columns="columns" :params="params" api="/role" primary-key="roleId" selection>
            <template #button="{selections}">
                <el-button v-auth="'role:add'" @click="onEdit('create', selections)"/>
                <el-button v-auth="'role:delete'" @click="onDelete(selections)" :disabled="!(selections?.length > 1)" type="danger"/>
            </template>
            <template #search>
                <el-form-item label="英文名称" prop="roleName">
                    <el-input v-model="params.roleName"/>
                </el-form-item>
                <el-form-item label="中文名称" prop="alias">
                    <el-input v-model="params.alias"/>
                </el-form-item>
            </template>
        </data-table>

        <edit ref="editRef"/>
    </main-page>
</template>